package com.zhenyi.liuxue.admin;

import java.util.ArrayList;
import java.util.List;

import com.cjw.model.DBMap;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.liuxue.common.model.LxCertificate;
import com.liuxue.common.model.LxCertificateItem;
import com.liuxue.common.model.LxCertificateItemQuestion;
import com.liuxue.common.model.LxCompany;
import com.liuxue.common.model.LxRange;
import com.liuxue.common.model.LxSchool;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;

public class CertController extends AdminController {
	
	public void list() {
		String keyword = getPara("keyword");
		Kv kv = Kv.create();
		if (StrKit.notBlank(keyword)) {
			kv.set("keyword", keyword);
			setAttr("keyword", keyword);
		}
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXAdminFindCertificate", kv);
		Page<LxCertificate> pages = LxCertificate.dao.paginate(getPage(), getPageSize(), sqlPara);
		setRainbow(pages);
		setItems(JsonKit.toJson(pages.getList()));
		render("/lx/admin/cert/index.html");
	}
	
	public void info() {
		setReferer();
		Long certificateId = getParaToLong("certificateId");
		if (certificateId != null) {
			LxCertificate info = LxCertificate.dao.findById(certificateId);
			if (info == null) {
				renderFailure(404, "not found");
				return;
			}
			
			if (info.getRangeType().equals(2)) {
				Kv kv = Kv.create();
				kv.set("certId", certificateId);
				SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindItemRange", kv);
				List<LxRange> rangeList = LxRange.dao.find(sqlPara);
				ArrayList<DBMap> locationLimit = new ArrayList<>();
				for (LxRange range : rangeList) {
					DBMap map = new DBMap();
					map.put("province", range.getProvince());
					map.put("city", range.getCity());
					locationLimit.add(map);
				}
				info.put("locationLimit", locationLimit);
				
			} else if (info.getRangeType().equals(3)) {
				Kv kv = Kv.create();
				kv.set("certId", certificateId);
				SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindItemRange", kv);
				List<LxRange> rangeList = LxRange.dao.find(sqlPara);
				ArrayList<DBMap> companyLimit = new ArrayList<>();
				ArrayList<DBMap> locationLimit = new ArrayList<>();
				for (LxRange range : rangeList) {
					if (range.getCompanyId() != null) {
						DBMap map = new DBMap();
						map.put("id", range.getCompanyId());
						map.put("name", range.get("companyName"));
						companyLimit.add(map);
					}
					if (range.getLocation() != null) {
						String[] locationList = range.getLocation().split(",");
						DBMap map = new DBMap();
						map.put("province", locationList[0]);
						map.put("city", locationList.length > 1 ? locationList[1] : "");
						locationLimit.add(map);
					}
				}
				info.put("companyLimit", companyLimit);
				info.put("locationLimit", locationLimit);
			}
			setInfoItem(info);
		}
		List<LxSchool> schools = LxSchool.dao.findAll();
		SqlPara sqlPara2 = Db.use("liuxue").getSqlPara("LXFindCompanies");
		List<LxCompany> companies = LxCompany.dao.find(sqlPara2);
		setAttr("schools", schools);
		setAttr("companies", JsonKit.toJson(companies));
		render("/lx/admin/cert/info.html");
	}
	
	public void submit() {
		Long certificateId = getParaToLong("certificateId");
		String title = getPara("title");
//		String desc = getPara("desc");
		String image = getPara("image");
		Long schoolId = getParaToLong("schoolId");
		Long sort = getParaToLong("sort", 99999L);
		Integer status = getParaToInt("status", 1);
		String startTime = getPara("startTime");
		String endTime = getPara("endTime");
		Integer rangeType = getParaToInt("rangeType");
		String companyLimit = getPara("companyLimit");
		String locationLimit = getPara("locationLimit");
		
		DateTime start = DateUtil.parse(DateUtil.parse(startTime).toString("yyyy-MM-dd 00:00:00"));
		DateTime end = DateUtil.parse(DateUtil.parse(endTime).toString("yyyy-MM-dd 23:59:59"));
		
		LxCertificate info = null;
		if (certificateId == null) {
			info = new LxCertificate();
			info.setSort(sort);
			info.setStatus(status);
			info.save();
		} else {
			info = LxCertificate.dao.findById(certificateId);
			if (info == null) {
				renderFailure(404, "not found");
				return;
			}
		}
		info.setTitle(title);
//		info.setDesc(desc);
		info.setImage(image);
		info.setSchoolId(schoolId);
		info.setSort(sort);
		info.setStatus(status);
		info.setStartTime(start);
		info.setEndTime(end);
		info.setRangeType(rangeType);
		boolean flag = info.update();
		if (flag) {
			// 处理可见范围
			Kv kv = Kv.create();
			if (certificateId != null) {
				kv.set("certId", info.getId());
				SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindItemRange", kv);
				List<LxRange> rangeList = LxRange.dao.find(sqlPara);
				for (LxRange range : rangeList) {
					range.delete();
				}
			}
			if ((rangeType.equals(2) || rangeType.equals(3)) && StrKit.notBlank(locationLimit)) {
				String[] locations = locationLimit.split(";");
				for (String loc : locations) {
					kv.set("certId", info.getId());
					kv.set("location", loc);
					SqlPara sp = Db.use("liuxue").getSqlPara("LXFindItemRange", kv);
					LxRange range = LxRange.dao.findFirst(sp);
					if (range == null) {
						range = new LxRange();
						range.setCertId(info.getId());
						range.setLocation(loc);
						String[] provinceCity = loc.split(",");
						range.setProvince(provinceCity[0]);
						if (provinceCity.length > 1) {
							range.setCity(provinceCity[1]);
						} else {
							range.setCity("");
						}
						range.save();
					}
				}
			}
			if (rangeType.equals(3) && StrKit.notBlank(companyLimit)) {
				String[] idStrs = companyLimit.split(";");
				for (String idStr : idStrs) {
					kv.set("certId", info.getId());
					kv.set("companyId", idStr);
					SqlPara sp = Db.use("liuxue").getSqlPara("LXFindItemRange", kv);
					LxRange range = LxRange.dao.findFirst(sp);
					if (range == null) {
						range = new LxRange();
						range.setCertId(info.getId());
						range.setCompanyId(Long.valueOf(idStr));
						range.save();
					}
				}
			}
		}
		renderFlag(flag);
	}
	
	public void delete() {
		Long certificateId = getParaToLong("certificateId");
		if (certificateId == null) {
			renderFailure(500, "id is null");
			return;
		}
		LxCertificate info = LxCertificate.dao.findById(certificateId);
		if (info == null) {
			renderFailure(404, "not found");
			return;
		}
		info.setFlag(1);
		renderFlag(info.update());
	}
	
	public void courseList() {
		Long certificateId = getParaToLong("certificateId");
		if (certificateId == null) {
			renderFailure(500, "cert id is null");
			return;
		}
		LxCertificate cert = LxCertificate.dao.findById(certificateId);
		if (cert == null) {
			renderFailure(404, "not found");
			return;
		}
		Kv kv = Kv.create();
		kv.set("certificateId", certificateId);
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXAdminFindCourse", kv);
		Page<LxCertificateItem> pages = LxCertificateItem.dao.paginate(getPage(), getPageSize(), sqlPara);
		setRainbow(pages);
		setItems(JsonKit.toJson(pages.getList()));
		setAttr("certificate", JsonKit.toJson(cert));
		render("/lx/admin/cert/courseList.html");
	}
	
	public void courseInfo() {
		setReferer();
		Long courseId = getParaToLong("courseId");
		Long certificateId = getParaToLong("certificateId");
		if (courseId != null) {
			LxCertificateItem info = LxCertificateItem.dao.findById(courseId);
			if (info == null) {
				renderFailure(404, "not found");
				return;
			}
			setInfoItem(info);
		}
		setAttr("certificateId", certificateId);
		render("/lx/admin/cert/courseInfo.html");
	}
	
	public void submitCourse() {
		Long courseId = getParaToLong("courseId");
		Long certificateId = getParaToLong("certificateId");
		String title = getPara("title");
		String duration = getPara("duration");
		String content = getPara("content");
		Integer sort = getParaToInt("sort", 99999);
		Integer status = getParaToInt("status", 1);
		Integer isVideo = getParaToInt("isVideo", 0);
		
		if (certificateId == null) {
			renderFailure(500, "cert id is null");
			return;
		}
		
		LxCertificateItem info = null;
		if (courseId == null) {
			info = new LxCertificateItem();
			info.setCertificateId(certificateId);
			info.setSort(sort);
			info.setStatus(status);
			info.save();
		} else {
			info = LxCertificateItem.dao.findById(courseId);
			if (info == null) {
				renderFailure(404, "not found");
				return;
			}
		}
		
		if (!content.contains("http://") && isVideo.equals(1)) {
			content = "http://v.polyv.net/uc/video/getMp4?vid=" + content;
		}
		
		info.setTitle(title);
		info.setDuration(duration);
		info.setContent(content);
		info.setSort(sort);
		info.setStatus(status);
		info.setIsVideo(isVideo);
		renderFlag(info.update());
	}
	
	public void deleteCourse() {
		Long courseId = getParaToLong("courseId");
		if (courseId == null) {
			renderFailure(500, "id is null");
			return;
		}
		LxCertificateItem info = LxCertificateItem.dao.findById(courseId);
		if (info == null) {
			renderFailure(404, "not found");
			return;
		}
		renderFlag(info.delete());
	}
	
	public void questionList() {
		Long courseId = getParaToLong("courseId");
		if (courseId == null) {
			renderFailure(500, "course id is null");
			return;
		}
		LxCertificateItem course = LxCertificateItem.dao.findById(courseId);
		if (course == null) {
			renderFailure(404, "course not found");
			return;
		}
		Kv kv = Kv.create();
		kv.set("courseId", courseId);
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXAdminFindCourseQuestion", kv);
		Page<LxCertificateItemQuestion> pages = LxCertificateItemQuestion.dao.paginate(getPage(), getPageSize(), sqlPara);
		setRainbow(pages);
		setItems(JsonKit.toJson(pages.getList()));
		setAttr("course", JsonKit.toJson(course));
		render("/lx/admin/cert/questionList.html");
	}
	
	public void questionInfo() {
		setReferer();
		Long questionId = getParaToLong("questionId");
		Long courseId = getParaToLong("courseId");
		if (questionId != null) {
			LxCertificateItemQuestion info = LxCertificateItemQuestion.dao.findById(questionId);
			if (info == null) {
				renderFailure(404, "not found");
				return;
			}
			setInfoItem(info);
		}
		setAttr("courseId", courseId);
		render("/lx/admin/cert/question.html");
	}
	
	public void submitQuestion() {
		Long questionId = getParaToLong("questionId");
		Long courseId = getParaToLong("courseId");
		String question = getPara("question");
		String answers = getPara("answers");
		Integer type = getParaToInt("type");
		Long sort = getParaToLong("sort", 99999L);
		Integer status = getParaToInt("status", 1);
		
		if (courseId == null) {
			renderFailure(500, "course id is null");
			return;
		}
		
		LxCertificateItemQuestion info = null;
		if (questionId == null) {
			info = new LxCertificateItemQuestion();
			info.setCertificateItemId(courseId);
			info.setSort(sort);
			info.setStatus(status);
			info.save();
		} else {
			info = LxCertificateItemQuestion.dao.findById(questionId);
			if (info == null) {
				renderFailure(404, "not found");
				return;
			}
		}
		info.setQuestion(question);
		info.setAnswers(answers);
		info.setType(type);
		info.setSort(sort);
		info.setStatus(status);
		renderFlag(info.update());
	}
	
	public void deleteQuestion() {
		Long questionId = getParaToLong("questionId");
		if (questionId == null) {
			renderFailure(500, "id is null");
			return;
		}
		LxCertificateItemQuestion info = LxCertificateItemQuestion.dao.findById(questionId);
		if (info == null) {
			renderFailure(404, "not found");
			return;
		}
		renderFlag(info.delete());
	}

}
